var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const fs = require("fs");
const JWT = require("./utils/JWT")
const router = express.Router()
const getTime = require("./utils/getTime")


var app = express();

//解决跨域
const cors = require('cors')
app.use(cors())

const multer = require("multer")    // nodejs用于上成文件的模块
let objMulter = multer({ dest: "./public/upload" });
//实例化multer，传递的参数对象，dest表示上传文件的存储路径
app.use(objMulter.any())//any表示任意类型的文件
// app.use(objMulter.image())//仅允许上传图片类型
 
app.use(express.static("./public"));//将静态资源托管，这样才能在浏览器上直接访问预览图片或则html页面


// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// 验证token中间件
app.use((req, res, next) => {
  // 如果token有效 ,next()
  // 如果token过期了, 返回401错误
  /*
    首先排除登录注册接口
  */
  if (req.url === "/login" || "/register") {
    next();
    return;
  }
  const token = req.headers["authorization"];
  // token解析
  if (token) {
    var payload = JWT.verify(token);
    if (payload) {
      // 每一次请求,重新生成新的token
      const newToken = JWT.generate(
        {
          _id: payload._id,
          username: payload.username,
        },
        "7d"
      );
      res.header("Authorization", newToken);
      next();
    } else {
      res.status(401).send({ code: "-1", error: "token过期" });
    }
  }
});
// 图片上传接口
const filesUpload = router.post("/files/upload",(req, res) => {
  let oldName = req.files[0].filename; 
  let originalname = req.files[0].originalname; 
  // 取无后缀的文件名
  let ex_name = originalname.split(".")[0];
  //防止文件名重复，为文件名加上时间戳
  let fileName = ex_name + "-" + Date.now() + path.extname(originalname);
  //fileName就是上传文件的文件名
  fs.renameSync("./public/upload/" + oldName, "./public/upload/" + fileName); //改图片的名字注意此处一定是一个路径，而不是只有文件名
  return res.send({
    url: "http://localhost:3000/upload/" + fileName,
  });
})
app.use("/",filesUpload)

// 前台接口
const userRouter = require("./routes/web/user");
const shopcartRouter = require("./routes/web/shopcart")
const orderRouter = require("./routes/web/order")
const messageRouter = require("./routes/web/message")
const policyRouter = require("./routes/web/policy")
const charProductRouter = require("./routes/web/charProduct")
const addressRouter = require("./routes/web/addresses")
const productRouter = require("./routes/web/product")
app.use("/", userRouter);
app.use("/shopcarts", shopcartRouter);
app.use("/orders", orderRouter);
app.use("/message", messageRouter);
app.use("/policy", policyRouter);
app.use("/charProduct", charProductRouter);
app.use("/address", addressRouter);
app.use("/product", productRouter);


// 后台接口
const adminRouter = require("./routes/api/admin")
const policyMasterRouter = require("./routes/api/policy")
const messageMasterRouter = require("./routes/api/message")
const adRouter = require("./routes/api/ad")
const userMasterRouter = require("./routes/api/user")
const orderMasterRouter = require("./routes/api/order")
const categoryRouter = require("./routes/api/category")
const productMasterRouter = require("./routes/api/product")
const charProductMasterRouter = require("./routes/api/charProduct")
const authRouter = require('./routes/api/auth')
app.use("/api", adminRouter)
app.use("/api", policyMasterRouter)
app.use("/api", messageMasterRouter)
app.use("/api", adRouter)
app.use("/api", userMasterRouter)
app.use("/api", orderMasterRouter)
app.use("/api", categoryRouter)
app.use("/api", productMasterRouter)
app.use("/api", charProductMasterRouter)
app.use("/api", authRouter)

// 捕获请求 传递404的中间件
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  // res.render('error');
  res.json({
    message: err.message,
    error: err,
  });
});

module.exports = app;
